<?php
declare(strict_types=1);

namespace App\AdminApi\Modular\User\Seaech;

use App\AdminApi\Modular\User\Service\UserService;
use App\Common\Enums\SexEnums;
use App\Common\Query\Query;
use Core\Basics\BasicsSearch;
use Hyperf\Database\Model\Builder;
use App\AdminApi\Modular\User\Service\{
    LevelService, TagsService
};
use Zms\Unit\Is;

class UserSearch extends BasicsSearch
{
    protected array $column = [
        "id",
        "avatar",
        "nickname",
        "mobile",
        "sex",
        "tags_ids",
        "level_id",
        "status",
        "created_at",
        "last_login",
        "deleted_at"
    ];

    public function query(): Builder
    {
        $where = $this->where;

        if (isset($where['is_recycle']) && intval($where['is_recycle']) === 1) {
            $query = container(UserService::class)->onlyTrashed();//仅查询软删除
        } else {
            $query = container(UserService::class)->query();//查询正常数据
        }

        if (isset($where['nickname']) && Is::notEmpty($where['nickname'])) {
            Query::LikeSearch($query, 'nickname', $where['nickname']);
        }
        if (isset($where['mobile']) && Is::notEmpty($where['mobile'])) {
            Query::LikeSearch($query, 'mobile', $where['mobile']);
        }
        if (isset($where['sex']) && Is::notEmpty($where['sex'])) {
            $query->where('sex', $where['sex']);
        }
        if (isset($where['level_id']) && Is::notEmpty($where['level_id'])) {
            $query->where('level_id', $where['level_id']);
        }
        if (isset($where['tags_ids']) && Is::notEmpty($where['tags_ids'])) {
            Query::FindInSetSearch($query, 'tags_ids', $where['tags_ids']);
        }
        if (isset($where['status']) && Is::notEmpty($where['status'])) {
            $query->where('status', $where['status']);
        }
        if (isset($where['created_at'][0]) && Is::notEmpty($where['created_at'][0])) {
            $query->where('created_at', '>=', strtotime($where['created_at'][0]));
        }
        if (isset($where['created_at'][1]) && Is::notEmpty($where['created_at'][1])) {
            $query->where('created_at', '<', strtotime($where['created_at'][1]));
        }
        return $query;
    }


    public function HanderData(array $data): array
    {
        foreach ($data as &$item) {
            $item['_sex'] = SexEnums::Explain($item['sex']);
        }
        $data = container(LevelService::class)->setJoinData($data, 'level_id', ['desc' => '_level']);
        return container(TagsService::class)->setJoinData($data, 'tags_ids', ['desc' => '_tags']);
    }
}